<?php
namespace Work\Controller;

use Think\Controller;

/**
 * 登录页面的控制器
 * @package Work\Controller
 */
class LoginController extends Controller{
    public function login(){

         //显示页面
        if(IS_GET){
            $this->display('login');
            return;
        }

        // 处理登陆
        $arr=[
            'cp_user' => $_POST['cp_user'] ,
            'cp_psw'  => $_POST['cp_psw']
        ];

        $ad_user = $_POST['cp_user'];
        /*
         *正则判断用户名格式
         *  */

        if (!preg_match('/^[a-zA-Z0-9_]{3,16}$/ ' , $_POST['cp_user'])){
            $this->error('用户名格式不正确','/Login/login');
        }

        /*
         * tp内置实例化对象
         * */
        $admin = D('company');

        /*
         * 进行条件查询
         * */

        $data = $admin->where($arr)->find();

        /*
         * 验证账户密码是否与数据库相同
         * */
        if (count($data) == 0) {

            $this->error('用户密码不正确','/Login/login');
        }
        else {
            $_SESSION['cp_user']  = $ad_user;
            $_SESSION['cp_id']    = $data['cp_id'];
            redirect('/Index/index');
        }
    }

    /*
     * 忘记密码功能
     * */

    public function forget_psw(){
        if (!IS_POST){
            $this->display();
            return;
        }
        $arr=[
            'cp_user' => $_POST['cp_user'],
            'cp_issue' => $_POST['cp_issue'],
        ];

        $cp_psw = $_POST['cp_psw'];
        $arr1 = [
            'cp_psw' => $cp_psw,
        ];

        $cp = D('company');

        $data = $cp->where($arr)->find();

        if (count($arr) == 0){
            $this->error('修改失败','/Login/forger');
        }
        else {
            $cp->where(['cp_id' =>$data['cp_id'] ])->setField($arr1);
            redirect('/Login/login');
        }

    }

    /*
     * 退出登录功能
     * */

    public function logout(){
        session_destroy();
        redirect('/Login/login');
    }
    /**
     * 企业管理员修改密码
     */
    public function chang_psw() {
        $data  = D('Company');
        $cp_id = $_SESSION['cp_id'];
        if (!IS_POST) {
            //未修改前获取用户名
            $arr = $data->where(['cp_id'=>$cp_id])->find();
            $arr['cp_user'];
            $this->assign('arr',$arr);
            $this->display('chang_psw');
            return;
        } else {
             //接收密码
            $pswj = $_POST['psw'];
            $pswx = $_POST['pswx'];
            $pswq = $_POST['pswq'];
            $arr = [
                'cp_psw' => $pswx
            ];
            $arr1 = [
                'cp_psw' => $pswj
            ];
            if ($pswx == $pswq) {
                $psw = $data->where(['cp_id' => $cp_id])->where($arr1)-save($arr);
                redirect('/Index/index');
            } else {
                $this->error('密码不一致','/Login/chang_psw');
            }
        }
    }
}